package com.tqjc.system.core.task;

import com.tqjc.system.common.constant.GlobalConstant;
import com.tqjc.system.common.constant.RemoteURLConstant;
import com.tqjc.system.common.entity.BO.PLCWriteRequestParamBO;
import com.tqjc.system.common.entity.BO.ResponseLabelDataBO;
import com.tqjc.system.common.enums.tankCarWeight.OriginalTankCarWeightInfoEnum;
import com.tqjc.system.common.enums.tankCarWeight.TankCarWeightInfoEnum;
import com.tqjc.system.core.util.PLCHttpsUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @description: 写值槽车重量任务
 * @Author: 86195
 * @Date: 2024/1/24 15:01
 **/
@Component
@Slf4j
public class WriteTankCarWeightTask {

    //每秒进行一次
    @Scheduled(cron = "0/1 * * * * ?")
    public void run(){
        log.info("WriteTankCarWeightTask写值槽车重量信息开始！！！");
        //1.每5秒读取值，获取重量
        Map paramMap = new HashMap(2);
        for (OriginalTankCarWeightInfoEnum weightInfoEnum : OriginalTankCarWeightInfoEnum.values()) {
            paramMap.put(GlobalConstant.STRING_SN,weightInfoEnum.getSn());
            paramMap.put(GlobalConstant.STRING_LABEL,weightInfoEnum.getLabel());
            try {
                ResponseLabelDataBO responseLabelDataBO = PLCHttpsUtils.sendPost(RemoteURLConstant.URL_READBC, paramMap, ResponseLabelDataBO.class);
                Map<String, String> content = responseLabelDataBO != null ? responseLabelDataBO.getContent() : null;
                if(content != null){
                    String currentVal = content.get("currentVal") != null ? content.get("currentVal") : null;
                    if(currentVal != null){
                        //2.写值至每台天车地址
                        this.writeWeightVal(currentVal,weightInfoEnum.getTankCarNO());
                    }
                }
            } catch (Exception e){
                log.error("WriteTankCarWeightTask写值任务出现异常",e);

            }

        }
        log.info("WriteTankCarWeightTask写值槽车重量信息结束！！！");
    }

    private void writeWeightVal(String weight,String tankCarNO) {
        TankCarWeightInfoEnum tankCarWeightInfoEnum = TankCarWeightInfoEnum.getEnumByTankCarNO(tankCarNO);
        Object[][] carPLCInfoArray = tankCarWeightInfoEnum.getCarPLCInfoArray();
        for (Object[] info : carPLCInfoArray) {
            //将重量信息写入每台天车
            PLCWriteRequestParamBO paramBO = PLCWriteRequestParamBO.builder().macSN((String) info[0]).address((String) info[1])
                    .dataType((Integer) info[2]).value(weight).build();
            try {
                PLCHttpsUtils.writeMoreVal(RemoteURLConstant.URL_WRITEBC,paramBO);
            } catch (Exception e){
                log.error("槽车号：{},天车：{},重量信息写值异常",tankCarNO,info[0],e);
            }
        }

    }

}
